import _ from 'lodash'
import { PAGE, DIC, INFO, SAVE } from '@/store/modules/crud/keys'
import * as api from '@/store/api/crud'
import { proxyActions } from '@/store/vuex-helper'
import { Commit } from 'vuex'
import { CrudStates } from '@/store/modules/crud/typings'

export default {
  [PAGE] ({ state, commit }: { state: CrudStates, commit: Commit }, { name }: { name: string}) {
    if (!state[name]) return
    return proxyActions(async () => {
      const response = await api.page(state[name].uri, state[name].search)
      commit(PAGE, { name, page: response.data })
    }, `${name}/${PAGE}`)
  },

  [DIC] ({ state, commit }: { state: CrudStates, commit: Commit }, { name }: { name: string }) {
    if (!state[name]) return
    return proxyActions(async () => {
      const response = await api.dic(state[name].uri)
      commit(DIC, {name, dic: response.data})
    }, `${name}/${DIC}`)
  },

  [INFO] ({ state, commit }: { state: CrudStates, commit: Commit }, { name, id }: { name: string, id:string}) {
    if (!state[name]) return
    return proxyActions(async () => {
      const response = await api.info(state[name].uri, id)
      commit(INFO, { name, info: response.data })
    }, `${name}/${INFO}`)
  },

  [SAVE] ({ state }: { state: CrudStates }, { name }: { name: string }) {
    if (!state[name]) return
    return _.get(state[name], 'info.id')
      ? proxyActions(() => api.modify(state[name].uri, state[name].info), `${name}/${SAVE}`)
      : proxyActions(() => api.create(state[name].uri, state[name].info), `${name}/${SAVE}`)
  }
}
